from flask import jsonify, g

from app.libs.error_code import DeleteSuccess
from app.libs.redprint import Redprint
from app.libs.token_auth import auth
from app.models.base import db
from app.models.user import User
from app.response.response import json_result

api = Redprint('user')


@api.route('/<int:uid>', methods=['GET'])
@auth.login_required
def get_user(uid):
    # token是否合法,是否过期

    # 常规操作
    # user = User.query.get(uid)
    # if not user:
    #     raise NotFound()

    # 简化操作
    user = User.query.filter_by(id=uid).first_or_404()
    # return jsonify(user)
    data = {
        "user": user,
        "test": 123
    }
    return json_result(data)


@api.route('', methods=['GET'])
@auth.login_required
def get_user():
    uid = g.user.id
    user = User.query.filter_by(id=uid).first_or_404()
    return jsonify(user)


# 管理员
@api.route('/<int:uid>', methods=['DELETE'])
def super_delete_user(uid):
    pass


@api.route('', methods=['DELETE'])
@auth.login_required
def delete_user():
    uid = g.user.uid
    with db.auto_commit():
        user = User.query.filter_by(id=uid).first_or_404()
        user.delete()
    return DeleteSuccess()


@api.route('/create', methods=['POST'])
def create_user():
    pass
